package cn.enjoy.mapstruct.mapconvert;

import cn.enjoy.mapstruct.entity.User;
import cn.enjoy.mapstruct.entity.UserVO1;
import cn.enjoy.mapstruct.entity.UserVO2;
import cn.enjoy.mapstruct.entity.UserVO3;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author K
 * @date 2021/7/27 下午4:51
 */
@Mapper(componentModel = "spring")
public interface UserCovert{

    UserCovert INSTANCE = Mappers.getMapper(UserCovert.class);


    /**
     * 字段数量类型数量相同，利用工具BeanUtils也可以实现类似效果
     */
    UserVO1 toConvertVO1(User source);

    User fromConvertEntity1(UserVO1 userVO1);

    /**
     * 字段数量类型相同,数量少：仅能让多的转换成少的，故没有fromConvertEntity2
     */
    UserVO2 toConvertVO2(User source);

//    @Mappings({
//            @Mapping(target = "createTime", expression = "java(cn.enjoy.mapstruct.mapconvert.DateTransform.strToDate(source.getCreateTime()))"),
//    })
//    UserVO3 toConvertVO3(User source);

    User fromConvertEntity3(UserVO3 userVO3);


    /**
     * 列表转换
     *
     * @param source      源列表
     * @param targetClass 目标class
     * @return List<T>
     */
    default <S, T> List<T> convertList(List<S> source, Class<T> targetClass) {
        return source.stream().map(x -> {
            T t;
            try {
                t = targetClass.getDeclaredConstructor().newInstance();

            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            t = (T) UserCovert.INSTANCE.toConvertVO1((User) x);
            return t;
        }).collect(Collectors.toList());
    }

}
